// pages/question_detail/question_detail.js
import Toast from '@vant/weapp/toast/toast';
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    questions:null,
    currentQuestion:null,
    prevQuestion:null,
    nextQuestion:null,
    currentIndex:null,
    showAnswer:false,
    recordPath:'',
    isPlaying:false,
    isCollect:false
  },
  toggle(){
    this.setData({
      showAnswer: !this.data.showAnswer
    })
  },
  prev(){
    this.setData({
      currentIndex:this.data.currentIndex-1,
      showAnswer:false,
      isCollect:false
    });
    if(this.data.currentIndex>=0){
      this.setData({
        currentQuestion:this.data.questions[this.data.currentIndex],
        prevQuestion:this.data.questions[this.data.currentIndex-1],
        nextQuestion:this.data.questions[this.data.currentIndex-1]
      })
      if(app.globalData.collectList.length!=0){
        for(let i =0; i < app.globalData.collectList.length; i++){
          if(app.globalData.collectList[i]._id===this.data.currentQuestion._id){
            this.setData({
              isCollect:true
            })
          }
        }
      }
    }
    return
  },
  next(){
    if(this.data.currentIndex<this.data.questions.length-1){
      this.setData({
        currentIndex:this.data.currentIndex-0+1,
        showAnswer:false,
        isCollect:false
      });
      this.setData({
        currentQuestion:this.data.questions[this.data.currentIndex],
        prevQuestion:this.data.questions[this.data.currentIndex-0+1],
        nextQuestion:this.data.questions[this.data.currentIndex-0+1]
      })
      if(app.globalData.collectList.length!=0){
        for(let i =0; i < app.globalData.collectList.length; i++){
          if(app.globalData.collectList[i]._id===this.data.currentQuestion._id){
            this.setData({
              isCollect:true
            })
          }
        }
      }
    }
    return
  },
  recording(){
    const recorderManager = wx.getRecorderManager()
    recorderManager.onStart(() => {
      console.log('recorder start')
    })
    recorderManager.onPause(() => {
      console.log('recorder pause')
    })
    recorderManager.onStop((res) => {
      console.log('recorder stop', res)
      const { tempFilePath } = res
      console.log('tempFilePath',tempFilePath);
      this.setData({
        recordPath:tempFilePath
      })
    })
    
    const options = {
      duration: 10000,
      sampleRate: 44100,
      numberOfChannels: 1,
      encodeBitRate: 192000,
      format: 'aac',
      frameSize: 50
    }
    
    recorderManager.start(options)
  },
  play(){
    if(!this.data.recordPath){
      Toast('请先录音！');
      return
    }
    this.setData({
      isPlaying:!this.data.isPlaying
    })
    const innerAudioContext = wx.createInnerAudioContext({
      useWebAudioImplement: false // 是否使用 WebAudio 作为底层音频驱动，默认关闭。对于短音频、播放频繁的音频建议开启此选项，开启后将获得更优的性能表现。由于开启此选项后也会带来一定的内存增长，因此对于长音频建议关闭此选项
    })
    innerAudioContext.src = this.data.recordPath
    if(this.data.isPlaying){
      innerAudioContext.play() // 播放
      innerAudioContext.onPlay(() => {
        console.log('开始播放11')
      })
      innerAudioContext.onTimeUpdate(()=>{
        console.log('playing');
      })
      innerAudioContext.onStop(()=>{
        console.log('播放结束');
        this.setData({
          isPlaying:false
        })
        // 播放完销毁
        InnerAudioContext.destroy()
      })
    }else{
      console.log('停止');
      this.setData({
        isPlaying:false
      })
      innerAudioContext.stop() // 停止
    }
    
  },
  toggleCollect(){
    if(app.globalData.token){
      this.setData({
        isCollect:!this.data.isCollect
      })
      // console.log();
      if(this.data.isCollect){
        app.globalData.collectList = [this.data.currentQuestion,...app.globalData.collectList]
      }
      else{
        for(let i = 0; i < app.globalData.collectList.length; i++){
          if(app.globalData.collectList[i]._id==this.data.currentQuestion._id){
            app.globalData.collectList = app.globalData.collectList.splice(i,1)
          }
        }
      }
    }
    else{
      Toast('请先登录！');
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // console.log('加载');
    console.log(options);
    this.setData({
      currentIndex:options.index
    })

    if(options.kw){
      const db = wx.cloud.database()
      db.collection('questions')
      .where({
        title:db.RegExp({
          regexp: options.kw,
          options:'i'
        })
      })
      .get()
      .then(res=>{
          this.setData({
            questions:res.data,
            currentQuestion:res.data[options.index]
          })
        })
    }else{
      const db = wx.cloud.database()
      // console.log(options.order);
      if(options.order=='0'){
        console.log('默认排序');
        if(options.type!='collect'){
          db.collection('questions').orderBy('order', 'asc').where({
            type:options.type
          })
          .get()
          .then((res)=>{
            console.log(res);
            this.setData({
              questions:res.data,
              currentQuestion:res.data[options.index]
            })
            if(app.globalData.collectList.length!=0){
              for(let i =0; i < app.globalData.collectList.length; i++){
                if(app.globalData.collectList[i]._id===this.data.currentQuestion._id){
                  this.setData({
                    isCollect:true
                  })
                }
              }
              
            }
          })
          .catch(console.error)
        }else{
          this.setData({
            questions:app.globalData.collectList,
            currentQuestion:app.globalData.collectList[options.index],
            isCollect:true
          })
        }
      }else if(options.order==1){
        console.log('降序');
        if(options.type!='collect'){
          db.collection('questions').orderBy('difficulty', 'desc')
          .where({
            type:options.type
          })
          .get()
          .then((res)=>{
            console.log(res);
            this.setData({
              questions:res.data,
              currentQuestion:res.data[options.index]
            })
          })
          .catch(console.error)
        }else{
          this.setData({
            questions:app.globalData.collectList,
            currentQuestion:app.globalData.collectList[options.index],
            isCollect:true
          })
        }
        
      }else{
        console.log('升序');
        if(options.type!='collect'){
          db.collection('questions').orderBy('difficulty', 'asc').where({
            type:options.type
          })
          .get()
          .then((res)=>{
            console.log(res);
            this.setData({
              questions:res.data,
              currentQuestion:res.data[options.index]
            })
          })
          .catch(console.error)
        }else{
          this.setData({
            questions:app.globalData.collectList,
            currentQuestion:app.globalData.collectList[options.index],
            isCollect:true
          })
        }
        
      }
      
    }
    console.log(app.globalData);
  },
})